
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

import '../Model/gm_login_user.dart';

class GMUserManager with ChangeNotifier {

  static final GMUserManager _instance = GMUserManager._internal();
  factory GMUserManager() => _instance;
  GMUserManager._internal();

  GMLoginUser? _user;

  GMLoginUser? get user => _user;

  // 判断用户是否登录
  // bool get isLoggedIn => _user != null;

  bool _isLoggedIn = false;
  bool get isLoggedIn => _isLoggedIn;

    // 检查本地是否保存了用户信息
  void checkLoginStatus() {
    // GMUserManager().loadUser;
    _isLoggedIn = true;
    notifyListeners();
  }
  
  // 保存用户信息到本地
  Future<void> saveUser(GMLoginUser user) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    String userString = json.encode(user.toJson());
    await prefs.setString('user', userString);
    _user = user;
  }

  // 从本地获取用户信息
  Future<void> loadUser() async {
    // _isLoggedIn = false;
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    String? userString = prefs.getString('user');
    if (userString!.isNotEmpty) {
      checkLoginStatus();
      _user = GMLoginUser.fromJson(json.decode(userString));
      
    }
    else {
      _isLoggedIn = false;
    }
  }

  // 注销用户
  Future<void> logout() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.remove('user');
    _user = null;
    _isLoggedIn = false;
    notifyListeners();
  }
}

